const express = require('express');
const bodyParser=require('body-parser');
const mysql = require('mysql');
var server = express();
server.listen(520);
server.use(express.static('public'));
server.use(bodyParser.urlencoded({
    extended: false
}));
//连接数据库，创建连接池对象
var pool = mysql.createPool({
    host:'47.56.253.106',
    port:'3306',
    user:'dj',
    password:'PfsKnfTf38ddTFkE',
    database:'dj',
    connectionLimit:15 //连接池的数量
})
server.post('/login',function (req,res) {
    //获取post请求的数据
    //console.log(req.body);
    //验证数据是否为空
    if(!req.body.uname){
        res.send({code:401,msg:'uname required'})
        return;
    }
    if(!req.body.upwd){
        res.send({code:401,msg:'upwd required'})
        return;
    }
    //执行SQL语句
    //查询数据中是否含有用户名和密码相匹配的数据
    pool.query('SELECT * FROM user WHERE uname=? AND upwd=?',[req.body.uname,req.body.upwd],function(err,result){
        if (err) throw err;
        //如果数组中有元素说明成功，没有元素失败
        if (result.length>0){
            //res.send({code:200,msg:'login suc'});
            //console.log(__dirname+"/public/login.html");
            res.redirect(302,'http://47.56.253.106:520/addjindu.html?uname='+req.body.uname);
        }else{
            res.send({code:301,msg:'login err'});
        }
    })})
//1.用户注册(增）
server.post('/addjindu',function (req,res) {
    //获取数据
    //console.log(req.body)
    //验证数据是否为空
    if (req.body.uname == ''){
        res.send({code:401,msg:'uname required'});
        //阻止往后执行
        return;
    }
    if (!req.body.ujd){
        res.send({code:402,msg:'ujd required'});
        return;
    }
    if (!req.body.date){
        res.send({code:403,msg:'date required'});
        return;
    }

    //把数据插入到数据库
    //执行SQL语句
    pool.query('INSERT INTO user SET ?',[req.body],function (err,result) {
        if(err) throw err;
        if(result.affectedRows>0) {
            res.redirect(302,'http://47.56.253.106:520');
        }
        return;
    })
    })

    // res.send('注册成功')

//查询用户列表 userlist get方法
server.get('/userlist',(req,res)=>{
    var sql="SELECT * from user";
    pool.query(sql,(err,result)=>{
        if (err) throw err;
        res.send(result);
    });
});
